package com.woniuxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.woniuxy.pojo.Department;
import com.woniuxy.pojo.Result;
import com.woniuxy.service.DepartmentService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("department")
@Api(tags = "科室管理接口")
@Slf4j
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;
    @GetMapping("/getDartment")
    @ApiOperation(value = "获取一级科室信息")
    public Result getDartment(){
        List<Department> departments = departmentService.getDartment();
        return Result.ok(departments);
    }
    @GetMapping("/getDartmentByLevel")
    @ApiOperation(value = "获取全部科室信息")
    public Result getDepartmentByLevel() {
        // 1. 获取所有科室数据
        List<Department> allDepartments = departmentService.list();

        // 2. 构建一级科室与二级科室的映射关系
        List<Map<String, Object>> resultList = new ArrayList<>();

        // 3. 获取所有一级科室
        List<Department> level1Departments = allDepartments.stream()
                .filter(d -> d.getLevel() == 1)
                .collect(Collectors.toList());

        // 4. 为每个一级科室构建数据
        for (Department level1 : level1Departments) {
            // 获取该一级科室下的所有二级科室
            List<Department> level2Departments = allDepartments.stream()
                    .filter(d -> d.getLevel() == 2 &&
                            d.getParentId() != null &&
                            d.getParentId().equals(level1.getId()))
                    .collect(Collectors.toList());

            // 将二级科室名称用顿号连接
            String level2Names = level2Departments.stream()
                    .map(Department::getName)
                    .collect(Collectors.joining("、"));

            // 构建返回数据
            Map<String, Object> item = new HashMap<>();
            item.put("level1", level1.getName());
            item.put("level2", level2Names);
            item.put("level1Id", level1.getId());
            item.put("level2Departments", level2Departments);

            resultList.add(item);
        }

        return Result.ok(resultList);
    }
    @PostMapping("/searchDepartment")
    @ApiOperation(value = "搜索科室信息")
    public Result searchDepartment( @RequestParam(required = false) String level1,
                                    @RequestParam(required = false) String level2) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("level", "parent_id", "id");
        //  1. 筛选条件
        //  1.1 筛选一级科室
        if (level1 != null) {
            queryWrapper.eq("parent_id", level1);
        }
        // 1.2 筛选二级科室
        if (level2 != null && !level2.isEmpty()) {
            queryWrapper.like("name", level2);
        }
        // 2. 查询数据
      List<Department> departments = departmentService.list();

        // 3. 处理数据格式
        List<Map<String, Object>> resultList = new ArrayList<>();
        // 获取所有一级科室
        List<Department> level1Departments = departments.stream()
                .filter(d -> d.getLevel() == 1)
                .collect(Collectors.toList());

        for (Department level : level1Departments) {
            // 获取该一级科室下的所有二级科室
            List<Department> level2Departments = departments.stream()
                    .filter(d -> d.getLevel() == 2 &&
                            d.getParentId() != null &&
                            d.getParentId().equals(level.getId()))
                    .collect(Collectors.toList());

            String level2Names = level2Departments.stream()
                    .map(Department::getName)
                    .collect(Collectors.joining("、"));

            Map<String, Object> item = new HashMap<>();
            item.put("level1", level.getName());
            item.put("level2", level2Names.isEmpty() ? "暂无二级科室" : level2Names);
            item.put("level1Id", level.getId());
            item.put("level2Departments", level2Departments);

            resultList.add(item);
        }

        return Result.ok(resultList);
    }
    @GetMapping("/getAllLevel2Departments")
    @ApiOperation(value = "获取所有二级科室信息")
    public Result getAllLevel2Departments() {
       QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
       queryWrapper.eq("level", 2).select("name");
       List<String> columns = new ArrayList<>();
       departmentService.listMaps(queryWrapper).forEach(map -> {
           columns.add(map.get("name").toString());
       });
       return Result.ok(columns);
    }
    @PostMapping("/updateDepartment")
    @ApiOperation(value = "更新科室信息")
    public Result updateDepartment(@RequestBody Map<String, Object> params) {
        try {
            // 1. 解析参数
            Integer level1Id = (Integer) params.get("id"); // 对应前端editForm.id
            List<String> level2Names = (List<String>) params.get("level2"); // 对应前端editForm.level2

            // 2. 验证参数
            if (level1Id == null) {
                return Result.fail("一级科室ID不能为空");
            }

            if (level2Names == null || level2Names.isEmpty()) {
                return Result.fail("二级科室列表不能为空");
            }

            // 3. 验证一级科室是否存在
            Department level1Department = departmentService.getById(level1Id);
            if (level1Department == null || level1Department.getLevel() != 1) {
                return Result.fail("一级科室不存在");
            }

            // 4. 删除该一级科室下的所有旧二级科室
            departmentService.remove(new QueryWrapper<Department>()
                    .eq("level", 2)
                    .eq("parent_id", level1Id));

            // 5. 创建新的二级科室
            List<Department> toSave = level2Names.stream()
                    .filter(name -> StringUtils.isNotBlank(name))
                    .map(name -> {
                        Department dept = new Department();
                        dept.setName(name.trim());
                        dept.setLevel(2);
                        dept.setParentId(level1Id);
                        dept.setStatus(1); // 1表示启用
                        dept.setCreateTime(new Date());
                        dept.setUpdateTime(new Date());
                        return dept;
                    })
                    .collect(Collectors.toList());

            // 6. 批量保存
            if (!toSave.isEmpty()) {
                departmentService.saveBatch(toSave);
            }

            return Result.ok("更新成功");
        } catch (Exception e) {
            return Result.fail("更新失败: " + e.getMessage());
        }
    }
}
